<template>
  <!-- 最外层容器：控制整体宽度和布局稳定性 -->
  <div class="dept-page-container">

    <!-- 顶部部门树区域 -->
    <div class="tree-top-section">
      <div class="tree-header">
        <span class="section-title">部门层级结构</span>
        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索部门名称"
          style="width: 240px; margin-left: 12px"
          @input="handleSearch"
        />
      </div>
      <!-- 部门树组件 -->
      <el-tree-v2
        ref="treeRef"
        :data="deptTreeData"
        :props="treeProps"
        :filter-method="filterNode"
        :height="160"
        style="border: 1px solid #ebeef5; border-radius: 4px; padding: 12px; margin-top: 8px"
      />
    </div>

    <!-- 操作栏 + 表格 + 分页区域 -->
    <div class="operation-table-section">
      <!-- 顶部操作按钮栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="dialogVisible2 = true">添加部门</el-button>
      </div>

      <!-- 表格容器（解决宽度缩小问题） -->
      <div class="table-container">
        <div class="table-wrapper">
          <el-table 
            :data="tableData" 
            border 
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', fontWeight: '500' }"
          >
            <el-table-column prop="id" label="部门编号" width="60" align="center" />
            <el-table-column prop="name" label="部门名称" width="90" align="center" />
            <el-table-column label="父部门编号" width="90" align="center">
              <template #default="scope">
                {{ scope.row.parentId === 0 ? '顶层部门' : scope.row.parentId }}
              </template>
            </el-table-column>
            <el-table-column prop="level" label="显示顺序" width="60" align="center" />
            <el-table-column label="状态" width="80" align="center">
              <template #default="scope">
                {{ formatStatus(scope.row.isDelete) }}
              </template>
            </el-table-column>
            <el-table-column prop="createdBy" label="创建人" width="70" align="center" />
            <el-table-column label="创建时间" width="160" align="center">
              <template #default="scope">
                {{ formatTime(scope.row.createdTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="updatedBy" label="更新人" width="70" align="center" />
            <el-table-column label="更新时间" width="160" align="center">
              <template #default="scope">
                {{ formatTime(scope.row.updatedTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary"
                  @click="opratorType='edit'; getDeptDetail(scope.row.id)"
                >编辑</el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="open(scope.row.id)"
                >删除</el-button>
                <el-button 
                  size="small" 
                  type="info"
                  @click="opratorType='detail'; getDeptDetail(scope.row.id)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

<!-- 分页条 -->
<div class="pagination">
  <el-pagination
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    :page-size="queryParams.size"
    :current-page="queryParams.page"
    :page-sizes="[5, 10, 20, 50]"
    @size-change="handleSizeChange"
    @current-change="handlePageChange"
    prev-text="上一页"
    next-text="下一页"
  >
  </el-pagination>
</div>
    </div>

    <!-- 编辑/详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="opratorType === 'detail' ? '部门详情' : '编辑部门'"
      width="500px"
      center
    >
      <el-form 
        :model="deptDetail" 
        label-width="100px" 
        style="padding: 20px"
      >
        <el-form-item label="部门编号">
          <el-input 
            v-model="deptDetail.id" 
            :disabled="opratorType === 'detail'" 
            readonly 
          />
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input 
            v-model="deptDetail.name" 
            :disabled="opratorType === 'detail'" 
            placeholder="请输入部门名称" 
          />
        </el-form-item>
        <el-form-item label="父部门编号">
          <el-input 
            v-model="deptDetail.parentId" 
            :disabled="opratorType === 'detail' || deptDetail.parentId === 0" 
            :placeholder="deptDetail.parentId === 0 ? '无' : '请输入父部门编号'" 
          />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input 
            v-model="deptDetail.level" 
            :disabled="opratorType === 'detail'" 
            placeholder="请输入显示顺序" 
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group 
            v-model="deptDetail.isDelete" 
            :disabled="opratorType === 'detail'"
          >
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建人">
          <el-input 
            v-model="deptDetail.createdBy" 
            readonly 
          />
        </el-form-item>
        <el-form-item label="更新人">
          <el-input 
            v-model="deptDetail.updatedBy" 
            readonly 
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input 
            :value="formatTime(deptDetail.createdTime)" 
            readonly 
          />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input 
            :value="formatTime(deptDetail.updatedTime)" 
            readonly 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="updateDept(deptDetail)"
            v-if="opratorType !== 'detail'"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增部门弹窗 -->
    <el-dialog 
      v-model="dialogVisible2" 
      title="新增部门" 
      width="420px" 
      center
    >
      <el-form 
        :model="Dept" 
        label-width="100px" 
        style="padding: 20px"
      >
        <el-form-item label="部门名称">
          <el-input 
            v-model="Dept.name" 
            placeholder="请输入部门名称" 
          />
        </el-form-item>
        <el-form-item label="父部门编号">
          <el-input 
            v-model="Dept.parentId" 
            placeholder="顶层部门填 0" 
          />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input 
            v-model="Dept.level" 
            placeholder="请输入显示顺序" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="creatDept">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import deptAPI from '../../api/dept';
import { ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox, ElTreeV2, ElPagination } from 'element-plus';

// 弹窗控制
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);

// 表格数据与分页
const tableData = ref([]);
const total = ref(0); // 总条数，用于分页显示


// 表单数据
const deptDetail = ref({
  id: '',
  name: '',
  parentId: '',
  level: '',
  isDelete: '',
  createdBy: '',
  updatedBy: '',
  createdTime: '',
  updatedTime: ''
});
const Dept = ref({ name: '', parentId: '', level: '' });
const opratorType = ref('');

// 分页查询参数（绑定分页组件）
const queryParams = ref({ 
  page: 1,  // 当前页码
  size: 10, // 每页条数
  name: '' 
});

// 树形结构相关
const deptTreeData = ref([]);
const treeProps = { value: 'deptId', label: 'name', children: 'children' };
const searchQuery = ref('');
const treeRef = ref();

// 初始化数据
onMounted(() => {
  getDeptList();
  getDeptTree();
});

// 获取部门列表（带分页）
const getDeptList = async () => {
  try {
    const res = await deptAPI.list(queryParams.value);
    tableData.value = res.data.sysDeptEntityList || [];
    total.value = res.data.totalRow || 0; // 从接口获取总条数
  } catch (error) {
    ElMessage.error('获取部门列表失败');
  }
};

// 获取部门树
const getDeptTree = async () => {
  try {
    const res = await deptAPI.getDeptTree();
    deptTreeData.value = res.data || [];
  } catch (error) {
    ElMessage.error('获取部门树失败');
  }
};

// 新增部门
const creatDept = async () => {
  try {
    const res = await deptAPI.createDept(Dept.value);
    if (res.code == 200) {
      getDeptList();
      getDeptTree(); // 新增后刷新部门树
      dialogVisible2.value = false;
      ElMessage.success('添加成功');
      Dept.value = { name: '', parentId: '', level: '' };
    } else {
      ElMessage.error('添加失败：' + res.message);
    }
  } catch (error) {
    ElMessage.error('网络异常，请重试');
  }
};

// 编辑部门
const updateDept = async (data) => {
  try {
    const res = await deptAPI.updateDept(data);
    ElMessage.success(res.message);
    dialogVisible.value = false;
    getDeptList();
    getDeptTree(); // 编辑后刷新部门树
  } catch (error) {
    ElMessage.error(error.message);
  }
};

// 删除部门
const deleteDept = async (id) => {
  try {
    await deptAPI.deleteDept(id);
    getDeptList();
    getDeptTree(); // 删除后刷新部门树
    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 确认删除弹窗
const open = (id) => {
  ElMessageBox.confirm(
    '确定删除该部门吗？删除后无法恢复',
    '警告',
    { type: 'warning' }
  )
    .then(() => deleteDept(id))
    .catch(() => ElMessage.info('已取消删除'));
};

// 获取部门详情
const getDeptDetail = async (id) => {
  try {
    const res = await deptAPI.getDeptById(id);
    deptDetail.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取详情失败');
  }
};

// 树形搜索功能
const filterNode = (query, node) => 
  node.name.toLowerCase().includes(query.toLowerCase());
const handleSearch = () => treeRef.value.filter(searchQuery.value);

// 分页事件处理
const handleSizeChange = (size) => {
  queryParams.value.size = size;
  queryParams.value.page = 1; // 切换每页条数时重置为第一页
  getDeptList();
};
const handlePageChange = (page) => {
  queryParams.value.page = page;
  getDeptList();
};

// 工具函数
const formatStatus = (status) => (status === 0 ? '正常' : '禁用');
const formatTime = (time) => (time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '');
</script>

<style scoped>
/* 最外层容器：设置最小宽度防止过度缩小 */
.dept-page-container {
  max-width: 1366px;
  min-width: 1000px; /* 核心：限制最小宽度 */
  margin: 0 auto;
  padding: 24px 16px;
  background-color: #fff;
  box-sizing: border-box; /* 确保内边距不影响宽度计算 */
}

/* 顶部部门树区域 */
.tree-top-section {
  background: #fcfcfc;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  width: 100%;
  box-sizing: border-box;
}
.tree-header {
  display: flex;
  align-items: center;
}
.section-title {
  font-size: 14px;
  font-weight: 500;
}

/* 操作栏 + 表格区域 */
.operation-table-section {
  background: #fcfcfc;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

/* 操作按钮栏 */
.operation-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

/* 表格容器：解决宽度缩小问题 */
.table-container {
  width: 100%;
  overflow-x: auto; /* 内容过宽时显示横向滚动条 */
  box-sizing: border-box;
}
.table-wrapper {
  min-width: 960px; /* 表格最小宽度，与外层容器匹配 */
}

/* 分页条样式 */
.pagination {
  margin-top: 16px;
  text-align: right;
  width: 100%;
  box-sizing: border-box;
  padding-top: 8px;
}

/* 弹窗样式 */
.el-dialog {
  --el-dialog-background-color: #fff;
}
.dialog-footer {
  text-align: right;
}

/* 响应式适配 */
@media (max-width: 1000px) {
  .dept-page-container {
    min-width: 900px;
    padding: 12px;
  }
  .table-wrapper {
    min-width: 860px;
  }
  .pagination {
    text-align: center;
  }
}
</style>